/**
 用到的listviewItem 是lmessage_all_item
 */
package org.buptsse.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.entity.HistoryItem;
import org.buptsse.entity.ShortMessage;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.HttpHelper;
import org.buptsse.utils.ImageService;
import org.buptsse.utils.JsonUtils;

import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MessageAllActivity extends Activity implements OnScrollListener,OnClickListener{
	// Button footerButton;
	// LinearLayout footerProgressBarLayout;// 加载进度滚动条
	// View view;
	ListAdapter listAdapter = new ListAdapter();
	ListView list;
	int visibleItemCount;
	
	int scrollState;
	LinkedList<ShortMessage> messageList = new LinkedList<ShortMessage>();
	int lastItem;
	int count;
	SharedPreferences preferences = null;

	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			pDialog.dismiss();
			switch (msg.what) {
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;
			case APPConstant.getMessageListError:
				Toast.makeText(getApplicationContext(), "没有相关内容", 1000).show();
				listAdapter.count=0;
				listAdapter.notifyDataSetChanged();
				break;
			case APPConstant.getMessageListFinish:
				messageList=(LinkedList<ShortMessage>) msg.obj;
				listAdapter.count=messageList.size();
				listAdapter.notifyDataSetChanged();
				break;
			}
			super.handleMessage(msg);
		}
	};
	private ProgressDialog pDialog;
	private Button backButton,refreshButton;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lmessage_all);
		listAdapter.count=0;
		list=(ListView)findViewById(R.id.message_list);
		list.setDivider(new ColorDrawable(Color.parseColor("#ecf6eb")));
		list.setDividerHeight(1);
		list.setVerticalFadingEdgeEnabled(false);
		list.setAdapter(listAdapter);
		list.setOnScrollListener(this);
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				ShortMessage message=messageList.get(arg2);
				//Bundle bundle=new Bundle();
				//bundle.putSerializable("message", message);
				//Toast.makeText(getApplicationContext(), ""+arg2, 1000).show();
				Intent intent=new Intent();
				intent.putExtra("message", message);
				intent.setClass(MessageAllActivity.this, MessageActivity.class);
				startActivity(intent);
			}
		});
		backButton=(Button) findViewById(R.id.rd_back);
		refreshButton=(Button) findViewById(R.id.rd_refresh);
		backButton.setOnClickListener(this);
		refreshButton.setOnClickListener(this);
		GetMessageListThread gmlt=new GetMessageListThread(getApplicationContext(), myHandler, GloableInstance.user.getName());
		gmlt.start();
		showWaittingDialog("正在加载内容");
	}

	public void showWaittingDialog(String msg)
	{
		pDialog=new ProgressDialog(this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
	}
	
	class ListAdapter extends BaseAdapter {
		int count = 10;
		@Override
		public int getCount() {
			return count;
		}
		@Override
		public Object getItem(int position) {
			return position;
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(MessageAllActivity.this);
			View view = inflater.inflate(R.layout.lmessage_all_item, null);
			ImageView userPhotoImageView=(ImageView) view.findViewById(R.id.user_photo);
			TextView userNameTextView=(TextView) view.findViewById(R.id.username);
			TextView messageCountTextView=(TextView) view.findViewById(R.id.message_count);
			ShortMessage msgItem=messageList.get(position);
			userPhotoImageView.setImageBitmap(ImageService.getImageByUrl(msgItem.getPhoto()));
			userNameTextView.setText(msgItem.getSender());
			messageCountTextView.setText(msgItem.getCount());
			return view;
		}
	}
	
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.visibleItemCount = visibleItemCount;
		lastItem = firstVisibleItem + visibleItemCount - 1;
		if (listAdapter.count >= count) {
			list.removeFooterView(view);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		this.scrollState = scrollState;
	}

	@Override
	public void onClick(View v) {
		int vid=v.getId();
		System.out.println("click"+vid);
		switch(vid){
		case R.id.rd_back:
			//返回按钮
			finish();
			break;
		case R.id.rd_refresh:
			//刷新按钮
			GetMessageListThread gmlt=new GetMessageListThread(getApplicationContext(), myHandler, GloableInstance.user.getName());
			gmlt.start();
			showWaittingDialog("正在加载内容");
			break;
		}
	}
	
	
	public class GetMessageListThread extends Thread
	{
		private Context context;
		private Handler handler;
		private String username;
		
		public GetMessageListThread(Context context , Handler handler,String username)
		{
			this.context=context;
			this.handler=handler;
			this.username=username;
		}
		
		public void run()
		{
			if(ConnectionChecker.CheckConnection(context, handler)==false)
			{
				return;
			}
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("username", username));
			try {
				String json=HttpHelper.sendPost(APPConstant.getMessageListUrl, param);
				System.out.println("json is:"+json);
				if(json.contains("failure"))
				{
					//失败
					Message msg=handler.obtainMessage(APPConstant.getMessageListError);
					handler.sendMessage(msg);
					return;
				}else
				{
					//成功
					@SuppressWarnings("unchecked")
					LinkedList<ShortMessage> list=(LinkedList<ShortMessage>) JsonUtils.getJsonObject(json, new TypeToken<LinkedList<ShortMessage>>() {}.getType());
					//System.out.println("list size is:"+list.size());
					Message msg=handler.obtainMessage(APPConstant.getMessageListFinish);
					msg.obj=list;
					handler.sendMessage(msg);
					return;
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
